#include "WorldLink.h"
#include "../gfx/RenderEngine.h"
namespace Putin{



WorldLink::WorldLink(Ogre::SceneManager* sceneMgr)
{
	// Save pointer to sceneMgr
	mSceneManager = sceneMgr;

	// Create RaySceneQuery
	mRaySceneQuery = sceneMgr->createRayQuery(Ogre::Ray());  
}

WorldLink::~WorldLink()
{
	// We created the query, and we are also responsible for deleting it.
	mSceneManager->destroyQuery(mRaySceneQuery);
}

float WorldLink::getHeight(Vec3f pos)
{
	Ogre::Vector3 ogre_pos = Ogre::Vector3(pos.x,pos.z,pos.y);
	queryRay = Ogre::Ray(ogre_pos + Ogre::Vector3::UNIT_Y*500, Ogre::Vector3::NEGATIVE_UNIT_Y);
	
	mRaySceneQuery->setRay(queryRay);

	Ogre::RaySceneQueryResult &result = mRaySceneQuery->execute();
	Ogre::RaySceneQueryResult::iterator itr = result.begin();
	
	float height;
	// Get the results
    if (itr != result.end() && itr->worldFragment)
    {
		height = itr->worldFragment->singleIntersection.y;
		return height;
    }
	return 0;
	
}
Vec3f WorldLink::getNormal(Vec3f pos){
	float f = 2;
	//We start with x gradient
	float a = getHeight(pos + Vec3f(-f,0,0));
	float b = getHeight(pos + Vec3f(f,0,0));
	float x = -(b-a)/2;

	a = getHeight(pos + Vec3f(0,-f,0));
	b = getHeight(pos + Vec3f(0,f,0));
	float y = -(b-a)/2;

	Vec3f normal = Vec3f(x,y,f).normalized();
	return normal;
	//return Vec3f(1,1,3).normalized();
}

Vec3f WorldLink::getUnitAABBhalfSize(int nr)
{
	std::ostringstream result;
	result << nr;
	return RenderEngine::instance().getUnitAABBhalfSize(result.str());
}

Vec3f WorldLink::getUnitOBBhalfSize(int nr)
{
	std::ostringstream result;
	result << nr;
	return RenderEngine::instance().getUnitOBBhalfSize(result.str());
}

}//End namespace Putin